function z = indepcorrz(r1, n1, r2, n2)
% indepcorrz  - independent correlation comparison z statistic
%
% FORMAT:       z = indepcorrz(r1, n1, r2, n2)
%
% Input fields:
%
%       r1, r2      N-D correlation values to compare
%       n1, n2      number of cases for r1, r2
%
% Output fields:
%
%       z           z-statistic for difference of correlations between
%                   r1 and r2

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 4 || ...
   ~isnumeric(r1) || ...
   ~isnumeric(r2) || ...
   ~isnumeric(n1) || ...
   ~isnumeric(n2) || ...
    isempty(r1) || ...
   ~isequal(size(r1), size(r2)) || ...
    numel(n1) ~= 1 || ...
    numel(n2) ~= 1 || ...
    isinf(n1) || ...
    isnan(n1) || ...
    n1 < 3 || ...
    n1 ~= round(n1) || ...
    isinf(n2) || ...
    isnan(n2) || ...
    n2 < 3 || ...
    n2 ~= round(n2)
    error( ...
        'BVQXtools:BadArgument', ...
        'Invalid argument (combination) given.' ...
    );
end

% set values to 0 where either is invalid
invval = (isinf(r1) | isnan(r1) | isinf(r2) | isnan(r2));
r1(invval) = 0;
r2(invval) = 0;

% transform to fisher z
r1 = fisherr2z(r1);
r2 = fisherr2z(r2);

% compute statistic
z = (1 / sqrt(1 / (n1 - 3) + 1 / (n2 - 3))) .* (r1 - r2);
